package com.sms.realm;

import java.util.Set;

import com.sms.pojo.User;
import com.sms.service.RoleService;
import com.sms.service.UserService;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

@Setter
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("查询授权");
        //获取用户名
        User user = (User) principals.getPrimaryPrincipal();
        //根据用户名查询权限
        Set<String> role = roleService.queryAllRoleNameByUserName(user.getUserName());
        //Set<String> permission = permissionService.queryAllPermissionByUserName(user.getUserName());
        //封装对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo(role);
//        simpleAuthorizationInfo.setStringPermissions(permission);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("在realm中查询身份");
        String username = (String) token.getPrincipal();
        User user = userService.queryUserByName(username);
        if (user == null) {
            return null;
        }
        ByteSource bytes = ByteSource.Util.bytes(user.getUserAccount());
        return new SimpleAuthenticationInfo(user, user.getPassword(), bytes, this.getName());
    }
}
